package it.koutifaris.testforclassutils;

class StackTraceHelper {

	private final Package packageToExclude;

	StackTraceHelper(Package packageToExclude) {
		this.packageToExclude = packageToExclude;
	}

	Class<?> getCallingClass() {
		Class<?> result;
		try {
			result = Class.forName(getCallingClassName());
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}

		return result;
	}

	String getCallingClassName() {
		final Throwable t = new Throwable();
		final StackTraceElement methodCaller = findStackTraceElement(t.getStackTrace());

		return methodCaller.getClassName();
	}

	private StackTraceElement findStackTraceElement(StackTraceElement[] stackTrace) {
		for (StackTraceElement stackTraceElement : stackTrace) {
			if (!isThisClass(stackTraceElement) && !isInExcludedPackage(stackTraceElement)) {
				return stackTraceElement;
			}
		}

		return null;
	}

	private boolean isInExcludedPackage(StackTraceElement stackTraceElement) {
		return stackTraceElement.getClassName().startsWith(packageToExclude.getName());
	}

	private boolean isThisClass(StackTraceElement stackTraceElement) {
		return stackTraceElement.getClassName().equals(this.getClass().getName());
	}
}
